package com.sjt.mylibrary.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串操作工具类
 */
public class StringUtil {
    /**
     * 使用系统默认字符集将字节数组转换为字符串
     *
     * @param bytes 字节数组
     * @return 转换结果
     */
    public static String bytes2string(byte[] bytes) {
        return bytes2string(bytes, null);
    }

    /**
     * 根据指定字符集将字节数组转换为字符串
     *
     * @param bytes    字节数组
     * @param encoding 字符集,如果为null则使用系统默认字符集
     * @return 转换结果
     */
    public static String bytes2string(byte[] bytes, String encoding) {
        if (bytes == null) {
            return null;
        }

        try {
            if (encoding == null) {
                return new String(bytes);
            } else {
                return new String(bytes, encoding);
            }
        } catch (Exception e) {
            Log.e("[UTIL]", "转换字节数组到字符串失败[" + encoding + "]");
            return null;
        }
    }

    /**
     * <p>
     * Checks if a String is empty ("") or null.
     * </p>
     * <p>
     * <pre>
     * StringUtils.isEmpty(null)      = true
     * StringUtils.isEmpty("")        = true
     * StringUtils.isEmpty(" ")       = false
     * StringUtils.isEmpty("bob")     = false
     * StringUtils.isEmpty("  bob  ") = false
     * </pre>
     * <p>
     * <p>
     * NOTE: This method changed in Lang version 2.0. It no longer trims the
     * String. That functionality is available in isBlank().
     * </p>
     *
     * @param str the String to check, may be null
     * @return <code>true</code> if the String is empty or null
     */
    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }

    /**
     * <p>
     * Replaces a String with another String inside a larger String, for the
     * first <code>max</code> values of the search String.
     * </p>
     * <p>
     * <p>
     * A <code>null</code> reference passed to this method is a no-op.
     * </p>
     * <p>
     * <pre>
     * StringUtils.replace(null, *, *, *)         = null
     * StringUtils.replace("", *, *, *)           = ""
     * StringUtils.replace("any", null, *, *)     = "any"
     * StringUtils.replace("any", *, null, *)     = "any"
     * StringUtils.replace("any", "", *, *)       = "any"
     * StringUtils.replace("any", *, *, 0)        = "any"
     * StringUtils.replace("abaa", "a", null, -1) = "abaa"
     * StringUtils.replace("abaa", "a", "", -1)   = "b"
     * StringUtils.replace("abaa", "a", "z", 0)   = "abaa"
     * StringUtils.replace("abaa", "a", "z", 1)   = "zbaa"
     * StringUtils.replace("abaa", "a", "z", 2)   = "zbza"
     * StringUtils.replace("abaa", "a", "z", -1)  = "zbzz"
     * </pre>
     *
     * @param text         text to search and replace in, may be null
     * @param searchString the String to search for, may be null
     * @param replacement  the String to replace it with, may be null
     * @param max          maximum number of values to replace, or <code>-1</code> if no
     *                     maximum
     * @return the text with any replacements processed, <code>null</code> if
     * null String input
     */
    public static String replace(String text, String searchString,
                                 String replacement, int max) {
        if (isEmpty(text) || isEmpty(searchString) || replacement == null
                || max == 0) {
            return text;
        }
        int start = 0;
        int end = text.indexOf(searchString, start);
        if (end == -1) {
            return text;
        }
        int replLength = searchString.length();
        int increase = replacement.length() - replLength;
        increase = (increase < 0 ? 0 : increase);
        increase *= (max < 0 ? 16 : (max > 64 ? 64 : max));
        StringBuffer buf = new StringBuffer(text.length() + increase);
        while (end != -1) {
            buf.append(text.substring(start, end)).append(replacement);
            start = end + replLength;
            if (--max == 0) {
                break;
            }
            end = text.indexOf(searchString, start);
        }
        buf.append(text.substring(start));
        return buf.toString();
    }

    /**
     * 替换指定字符串中所有特定内容
     *
     * @param str     要替换的字符串
     * @param find    要查找的字符串
     * @param replace 替换的字符串
     * @return 替换完的字符串
     */
    public static String replace(String str, String find, String replace) {
        return replace(str, find, replace, -1);
    }

    /**
     * 将参数值替换到字符串中<br>
     * 根据指定的参数数组中参数值替换字符串中的{数组索引号}
     * 例如信息为“我叫{0}，我今年{1}岁”，参数为{"张三","18"}，替换结果为“我叫张三，我今年18岁”
     *
     * @param str   要替换的字符串
     * @param paras 参数数组
     * @return
     */
    public static String replace(String str, String[] paras) {
        if (str != null && paras != null) {
            for (int i = 0; i < paras.length; i++) {
                String strValue = paras[i];

                if (strValue == null) {
                    strValue = "";
                }

                str = replace(str, "{" + i + "}", strValue);
            }
        }

        return str;
    }

    /**
     * 将参数值替换到字符串中<br>
     * 根据指定的参数集合中参数值替换字符串中的{集合元素索引号}
     * 例如信息为“我叫{0}，我今年{1}岁”，参数为{"张三","18"}，替换结果为“我叫张三，我今年18岁”
     *
     * @param str   要替换的字符串
     * @param paras 参数集合
     * @return
     */
    public static String replace(String str, List<String> paras) {
        if (str != null && paras != null) {
            for (int i = 0; i < paras.size(); i++) {
                String strValue = (String) paras.get(i);

                if (strValue == null) {
                    strValue = "";
                }

                str = replace(str, "{" + i + "}", strValue);
            }
        }

        return str;
    }

    /**
     * 将参数值替换到字符串中<br>
     * 根据指定的参数map中参数值替换字符串中的{参数名}，参数map给参数名、参数值对<br>
     * 例如信息为“我叫{name}，我今年{age}岁”，参数map为{("name","张三"),("age","18")}，替换结果为“我叫张三，
     * 我今年18岁”
     *
     * @param str   要替换的字符串
     * @param paras 融合参数，参数名、参数值对
     * @return
     */
    public static String replace(String str, Map<String, String> paras) {
        if (str != null && paras != null) {
            for (String strKey : paras.keySet()) {
                String strValue = paras.get(strKey);

                if (strValue == null) {
                    strValue = "";
                }

                str = replace(str, "{" + strKey + "}", strValue);

            }
        }

        return str;
    }

    public static String filterNull(String str){
        return isEmpty(str)?"--":str;
    }

    /**
     * 判断字符串是否是数字
     */
    private static Pattern p = Pattern.compile("^[-]?[\\d,]*[.]?\\d*$");

    public static boolean isNumber(String str) {
        if (str == null || str.toString().trim().length() == 0) {
            return false;
        }

        Matcher m = p.matcher(str);
        return m.find();
    }

    public static Spanned formatePrice(String price){
        if(isEmpty(price))price = "0.00";
        StringBuffer sb = new StringBuffer();
        sb.append("<small>¥ </small>")
                .append("<big>")
                .append(price)
                .append("</big>");
        return Html.fromHtml(sb.toString());
    }

    public static String[] getPhoneContacts(Uri uri, Context context) {
        if(uri == null)return null;
        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = context.getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            //取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex).trim().replaceAll(" ","");
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if (phone != null) {
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).trim().replaceAll(" ","");
            }
            phone.close();
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }

    /**
     * 判断手机号是否有效
     *
     * @param phoneNum 手机号
     * @return 有效则返回true, 无效则返回false
     */
    public static boolean isPhoneNumValid(String phoneNum) {
        return phoneNum.length() == 11 && phoneNum.matches("[0-9]{1,}");
    }

    /**
     * @param verifyCode 验证码
     * @return 同上
     */
    public static boolean isVerifyCodeValid(String verifyCode) {
        return verifyCode.length() > 3;
    }

    /**
     * @param password 用户输入密码
     * @return 有效则返回true, 无效则返回false
     */
    public static boolean isPasswordValid(String password) {
        return password.length() >= 6 && password.length() <= 16;
    }

    /**
     * 根据分隔符将List转换为String
     *
     * @param list
     * @param separator
     * @return
     */
    public static String listToString(final List<String> list, final String separator) {
        if (list == null || list.size() == 0) {
            return "";
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i)).append(separator);
        }
        if(isEmpty(separator))return sb.toString();
        return sb.toString().substring(0, sb.toString().length() - 1);
    }

    public static String DoubleRound2(Double d){
        if(d == null)return "";
        return String.format("%.2f",d);
    }

}
